import os
import tkinter as tk
from tkinter.filedialog import askopenfilename

import pandas as pd
import requests


class AskForFileFrame(tk.Frame):
    def __init__(self, row_num, parent, *args):
        self.row_num = row_num
        self.parent = parent
        self.path = tk.StringVar()
        super().__init__(self.parent, *args)

        self.path_Entry = tk.Entry(self, textvariable=self.path)
        self.path_Entry.pack(
            side="left", ipadx=70, ipady=4, padx=3
        )

        self.btn_ask_for_file = tk.Button(
            self, command=self.ask_for_file, text="浏览"
        )
        self.btn_ask_for_file.pack(side="left")

        self.btn_clear = tk.Button(
            self, command=self.clear_entry, text="清空"
        )
        self.btn_clear.pack(side="left")

        self.btn_add = tk.Button(
            self, command=self.create_frame, text="+"
        )
        self.btn_add.pack(side="left")

        if row_num >= 1:
            self.btn_destroy = tk.Button(
                self, command=self.destroy_frame, text="-"
            )
            self.btn_destroy.pack(side="left")


    def create_frame(self):
        frame = AskForFileFrame(self.row_num+1, self.parent)
        self.parent.ask_for_file_frame.append(frame)
        self.parent.fresh()

    def destroy_frame(self):
        self.parent.ask_for_file_frame.pop().destroy()
        self.parent.fresh()

    def clear_entry(self):
        self.path.set("")

    def ask_for_file(self):
        self.path.set(
            askopenfilename(filetypes=[
                ("CSV UTF-8(逗号分隔)", "*.csv"), ("json", "*.json")
            ])
        )


class Root(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("下载音频")

        self.word_reciting_ui = None

        self.all_AskForFileFrame = tk.Frame(self)
        self.all_AskForFileFrame.ask_for_file_frame = []
        self.all_AskForFileFrame.fresh = lambda: self.fresh()

        self.all_AskForFileFrame.ask_for_file_frame.append(
            AskForFileFrame(0, self.all_AskForFileFrame)
        )

        self.btn_row = 1
        self.btn = tk.Button(
            self, text="确认", command=self.get_file
        )

        self.bind("<Return>", lambda _: self.get_file())

        self.fresh()

        self.mainloop()

    def fresh(self):  # 刷新显示
        self.all_AskForFileFrame.pack(
            side="top", padx=50, expand=1
        )
        self.btn.pack(side="top", pady=5, expand=1)
        for frame in self.all_AskForFileFrame.ask_for_file_frame:
            frame.pack(side="top", expand=1, fill="both")

    def get_file(self):
        paths = []
        for i in range(len(self.all_AskForFileFrame.ask_for_file_frame)):
            path = self.all_AskForFileFrame.ask_for_file_frame[i].path.get()
            if path != '' and path[-1] == os.sep:  path = path[:-1]
            if os.path.exists(path):
                paths.append(path)
            else:
                print("not exists.")
        if paths != []:
            for path in paths:
                df = pd.read_csv(path)
                for word in df["单词"].tolist():
                    mp3_path = os.sep.join(
                        path.split(os.sep)[:-1]
                        + [path.split(os.sep)[-1].split('.')[0]]
                    )
                    if not os.path.exists(mp3_path):
                        os.mkdir(mp3_path)
                    self.download(word, mp3_path)

    def download(self, word, path, lan="uk"):
        try:
            # 音频来源：百度翻译
            url_word_mp3 = f"https://fanyi.baidu.com/gettts?lan={lan}&text={word}&spd=3&source=web"

            r = requests.get(url_word_mp3)

            with open(f"{path + os.sep + word}.mp3", "wb") as f:
                f.write(r.content)
                f.close()
        except:
            pass


root = Root()
